﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using System.Drawing;
using DAL;
using BOL;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;
using UtilityExtensions;
namespace UILGestion.Control
{
    public partial class ECItemSeleccionMonPanel : System.Web.UI.UserControl
    {
        public ECItemSeleccionMonPanel()
            {
                     ecBol= new EstructuraCostoBL();
            }


        private EstructuraCostoBL ecBol;

        public List<EstructuraCostoItemConfInfo> ItemLista
        {
            get
            {
                List<EstructuraCostoItemConfInfo> ItemLista = new List<EstructuraCostoItemConfInfo>();

                var lista = (List<EstructuraCostoItemConfInfo>)Session[idRecursoPartirList.Value.ToString()];

                foreach (GridViewRow row in itemGridView.Rows)
                {
                    CheckBox cb = (CheckBox)(row.FindControl("chkEmployeeSelector"));
                    if (cb != null && cb.Checked)
                    {
                        Int32 employeeId = (Int32)itemGridView.DataKeys[row.RowIndex].Value;
                        EstructuraCostoItemConfInfo item = lista.Single(p => p.idInternal == employeeId);
                        ItemLista.Add(item);
                    }
                }

                return ItemLista;
            }
        }

        public int idMoneda
        {
            get
            {
                return int.Parse(MonedaDropDown.SelectedValue);
            }
        }


      

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                
                if (!this.IsPostBack)
                {
                    idObra.Value = (string)Request.QueryString["idObra"];
                    idEstructuraCosto.Value = (string)Request.QueryString["idEC"];
                    FormatForm();

                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

            //FormatForm();

        }
      
        public void LoadRecurso(int idEstructuraCosto,int idMoneda,string idListYaUtilizado,string orden=default(string))
        {
            try
            {
                this.idEstructuraCosto.Value = idEstructuraCosto.ToString();

                List<ComparativoItemInfo> ds = (List<ComparativoItemInfo>)System.Web.HttpContext.Current.Session[idListYaUtilizado];
                if (ds == null)
                {
                    ds = new List<ComparativoItemInfo>();
                }


                IEnumerable<int> itemYaUtilizado = ds.Select(p => p.idEstructuraCostoItem);


                List<EstructuraCostoItemConfInfo> q = 
                  this.ecBol.getEstructuraCostoItemConfigDisp(
                   idEstructuraCosto,
                  idMoneda,
                  itemYaUtilizado,
                  0,
                  150,
                  orden);
               
               //retiramos los que tiene ordenCompra
                 

                 q.RemoveAll(p=>p.idOrdenCompraItemRef!=null);
                
                //debe de restar los que ya se encuentran utilizados

                idListYaUtilizados.Value = idListYaUtilizado;

                MonedaDropDown.SelectedValue = idMoneda.ToString();
                MonedaDropDown.Enabled = true;
                
                
                Session[idRecursoPartirList.Value.ToString()] = q;

                Moneda moneda = DbUtil.Db.Monedas.Single(p => p.idInternal == idMoneda);

                simbolMoneda.Value = moneda.simbol;


                BindDataItem();
                setEstadistica();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        private void FormatForm()
        {


            idRecursoPartirList.Value = Parametros.GenerarID().ToString();
           

            //var e = from i in DbUtil.Db.EstructuraCostos
            //        where i.idObra == int.Parse(idObra.Value)
            //        orderby i.descripcion
            //        select i;

            //EstructuraCosto view = new EstructuraCosto();
            //view.descripcion = "-------Seleccion de Estructrura Costo-----";
            //view.idInternal = 0;

            //List<EstructuraCosto> listaEC = new List<EstructuraCosto>();
            //listaEC.Add(view);
            //listaEC.AddRange(e.ToList());

           
            var m = DbUtil.Db.Monedas;
            MonedaDropDown.DataTextField = "descripcion";
            MonedaDropDown.DataValueField = "idInternal";

            MonedaDropDown.DataSource = m.ToList();
            MonedaDropDown.DataBind();

           


            List<EstructuraCostoItemConfInfo> itemList2 = new List<EstructuraCostoItemConfInfo>();
            List<OrdenCompraListInfo> itemList1 = new List<OrdenCompraListInfo>();
            Session[idRecursoPartirList.Value.ToString()] = itemList2;
            Session[idRecursoOCList.Value.ToString()] = itemList1;
           


        }


        private void resetEmpty()
        {
            if (itemGridView.Rows.Count == 0)
            {
                List<EstructuraCostoItemConfInfo> itemList0 = new List<EstructuraCostoItemConfInfo>();
                EstructuraCostoItemConfInfo itemcero = new EstructuraCostoItemConfInfo();
                itemcero.idInternal = 0;
                itemList0.Add(itemcero);
                itemGridView.DataSource = itemList0;
                itemGridView.DataBind();
                itemGridView.Rows[0].Visible = false;
            }

        }
        private void setEstadistica()
        {
            List<EstructuraCostoItemConfInfo> itema = this.ItemLista;

            
            TotalLabel.Text = String.Format("{0} {1:N}", simbolMoneda.Value, itema.Sum(p => p.totalDisp));
            totalUpdatePanel.Update();

        }
        private void BindDataItem()
        {

            List<EstructuraCostoItemConfInfo> item =
                (List<EstructuraCostoItemConfInfo>)Session[idRecursoPartirList.Value.ToString()];


            itemGridView.DataSource = item;
            itemGridView.DataBind();
            resetEmpty(); //necesario para add

            seleccionUpdatePanel.Update();
           

            UpdatePanelGrilla.Update();

           



        }
       
        protected void MonedaSeleccionDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {

                LoadRecurso(idEstructuraCosto.Value.ToInt(),int.Parse(MonedaDropDown.SelectedValue), idListYaUtilizados.Value);

               


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }
        protected void ItemAllSelectChange(object sender, EventArgs e)
        {
            //solo los seleccionados
            //seleccionamos todos los  item
            foreach (GridViewRow row in itemGridView.Rows)
            {
                CheckBox cb = (CheckBox)(row.FindControl("chkEmployeeSelector"));
                cb.Checked = ((CheckBox)sender).Checked;
            }
            UpdatePanelGrilla.Update();
            setEstadistica();

        }
        protected void ItemSelectChange(object sender, EventArgs e)
        {
            //solo los seleccionados
            //seleccionamos todos los  item
                       
            setEstadistica();

        }
        protected string GetSortDirection(string column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.

            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }

        protected void gridview_sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {

                string orden = e.SortExpression + " " + GetSortDirection(e.SortExpression);

                LoadRecurso(idEstructuraCosto.Value.ToInt(),int.Parse(MonedaDropDown.SelectedValue), idListYaUtilizados.Value, orden);

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }







        }

        protected void estructuraDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (((DropDownList)sender).Items.Count > 0)
                {
                    // cargamos las estructuras de costo necesarias 
                    idEstructuraCosto.Value = ((DropDownList)sender).SelectedValue;
                    if (idEstructuraCosto.Value != "0")
                    {
                       
                        LoadRecurso(idEstructuraCosto.Value.ToInt(),this.idMoneda, this.idListYaUtilizados.Value);
                        

                      }
                   
                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }

        //protected void proveedorSelect(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        if (((DropDownList)sender).Items.Count > 0)
        //        {
        //            // cargamos las estructuras de costo necesarias 
        //            idEstructuraCosto.Value = ((DropDownList)sender).SelectedValue;
        //            if (idEstructuraCosto.Value != "0")
        //            {
        //                LoadRecurso(idEstructuraCosto.Value.ToInt(),this.idMoneda, this.idListYaUtilizados.Value);

        //            }

        //        }
        //    }
        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);
        //        ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
        //         "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //        ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
        //         "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //    }
        //}
            
    }
}